package com.zxs.seckillservice.task;

import com.zxs.constant.Constants;
import com.zxs.entity.Goods;
import com.zxs.seckillservice.service.impl.GoodsServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;

import java.util.List;

@EnableScheduling  //开启定时任务
@Component
public class GoodsTask {

    @Resource
    private GoodsServiceImpl goodsService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 秒杀商品缓存任务
     * 开启定时任务，将商品缓存到数据库中  每3秒执行一次
     */
    @Scheduled(cron = "0/40 * * * * *")
    public void GoodsCache() {
        //获取数据库中的全部商品信息
        List<Goods> goodsList = goodsService.list();

        //遍历商品集合，把每个商品都存储到Redis中
        goodsList.forEach(goods -> {
            System.out.println("goods = " + goods);
            ValueOperations ops = redisTemplate.opsForValue();
            //将商品信息存储在redis中
            ops.set(Constants.REDIS_GOODS + goods.getId(), goods);

            //将商品的库存单独存储在redis中
            //setIfAbsent ：如果key不存在，则设置值，如果key存在，则不设置值
            //为了防止redis中减少了库存，但数据库还没有减少  定时任务扫描到重新设置了库存
            ops.setIfAbsent(Constants.REDIS_STORE + goods.getId(), goods.getStore());

        });

    }

}
